<?php

namespace app\common\service;
use think\facade\Log;
use think\facade\Config;
class CommonWxMessageService
{
    public static function orderSendMsgSend($openid,$o_pro_num,$post_num,$p_name,$page = "pages/order/orderList"){
        $tmpl_id = "_EFOCibPbsI1d0XARZNuZVSkm6LcvncefkccHdvOtgc";
        $info = [
            "character_string4"=>[
                'value' => $o_pro_num
            ],
            "character_string3"=>[
                'value' => $post_num
            ],
            "thing10"=>[
                'value' => $p_name
            ],
            "time7"=>[
                'value' => date("Y-m-d H:i:s",time())
            ],
        ];
        Log::info($info);
        @self::send_template($openid,$tmpl_id,$info,$page);
    }


    public static function send_template($openid,$tmpl_id,$info,$page= '/pages/home/home')
    {

        // 获取acceess_token
        $appid = Config::get("app.wx_xcx_AppID");
        $appscert = Config::get("app.wx_xcx_AppSecret");


        $access_token = self::getAccessToken($appid, $appscert);
        if (isset($access_token['errcode'])) {
            ajaxReturn(['status' => -1, 'msg' => '获取access_token失败', 'data' => $access_token]);
        }
        //发送内容格式
        $data = [
            'touser' => $openid,
            'template_id' => $tmpl_id,
            'miniprogramState' => 'formal',//developer为开发版；trial为体验版；formal为正式版；默认为正式版
            'page' => $page,
            'data' => $info,
        ];
        //发送
        $url = 'https://api.weixin.qq.com/cgi-bin/message/subscribe/send?access_token=' . $access_token;
        $result = CommonCurlService::post($url,json_encode($data));//CurlService::getInstance()->post($url,json_encode($data))
        $result = json_decode($result, true);

        //access_token过期处理
        if ($result['errcode'] == 40001) {
            //重新发送
            $access_token = self::getAccessToken($appid, $appscert);
            $url = 'https://api.weixin.qq.com/cgi-bin/message/subscribe/send?access_token=' . $access_token;
            $result = CurlService::getInstance()->post($url,json_encode($data));//httpRequest($url, 'POST', json_encode($data))
            $result = json_decode($result, true);
        }

        //结果处理
        if (isset($result['errcode']) && $result['errcode'] == 0) {     //成功
            return true;
        } else {
            //失败
            if ($result['errcode'] == 43101) {
                Log::info('用户拒绝接受消息：openid'.$openid);
            } elseif ($result['errcode'] == 47003) {
                Log::info('模板参数不准确，可能为空或者不满足规则'.$openid.$result['errmsg']);
            } elseif ($result['errcode'] == 40003) {
                Log::info('openid为空或者不正确'.$openid);
            }
        }
    }

    public static function subText($text, $length)
    {
        if (mb_strlen($text, 'utf8') > $length) {
            return mb_substr($text, 0, $length, 'utf8') . '......';
        } else {
            return $text;
        }
    }

    public static function getAccessToken($appid, $appsecret)
    {
        $url = 'https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=' . $appid . '&secret=' . $appsecret;
        $html = file_get_contents($url);
        $output = json_decode($html, true);
        $access_token = $output['access_token'];
        return $access_token;
    }
}